package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.multipart.MultipartFile;


public class FileUtil {

	/**
	 * 把服务器的缓存文件复制到本地目录
	 * @param file
	 * @param targetDir
	 * @param fileName
	 * @throws IOException
	 */
	public static void copyFile(MultipartFile file, String targetDir, String fileName) throws IOException {
		InputStream isRef = file.getInputStream();
		File targetDirFile = new File(targetDir);
		if (!targetDirFile.exists()) {
			targetDirFile.mkdirs();
		}
		File targetFile = new File(targetDir, fileName);
		FileOutputStream fosRef = new FileOutputStream(targetFile);
		IOUtils.copy(isRef, fosRef);
	}

	public static void outFile(String path, String fileName) {
		File filePath = new File(path);
		if (!filePath.exists())
			filePath.mkdir();
		HttpServletRequest request = 
				((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpServletResponse response=
				((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		try {
			response.setContentType("application/x-msdownload");
			FileInputStream FileInputStreamRef = new FileInputStream(new File(path + "\\" + fileName));
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			OutputStream osRef = response.getOutputStream();
			IOUtils.copy(FileInputStreamRef, osRef);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
